/*
 * @Date: 2024-03-01 21:57:22
 * @LastEditors: fromct 512799311@qq.com
 * @LastEditTime: 2024-03-01 22:59:22
 * @FilePath: /umi-max/src/pages/Home/pdfCom/index.tsx
 * @Description: pdf 导出图片 demo
 */

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { useMemo, useRef } from 'react';

const PdfComponent = () => {
  const tableRef = useRef<HTMLTableElement>(null);

  const columns = useMemo(() => {
    return [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '年龄',
        dataIndex: 'age',
        key: 'age',
      },
    ];
  }, []);

  const tableData = useMemo(() => {
    return new Array(100).fill(0).map((item, index) => {
      return {
        key: index,
        name: '张三' + index,
        age: 25,
      };
    });
  }, []);

  let chunks = [];
  for (let i = 0; i < tableData.length; i += 10) {
    chunks.push(tableData.slice(i, i + 10));
  }

  const exportToPdf = () => {
    const table = tableRef.current;

    if (!table) {
      return;
    }
    const pdf = new jsPDF('p', 'mm', 'a4'); // A4 paper size
    table.childNodes.forEach((child, index) => {
      html2canvas(child as HTMLTableElement).then((canvas) => {
        // 将 canvas 转换为图片数据
        const imgData = canvas.toDataURL('image/png');

        // 将图片添加到 PDF（缩放以适应页面）
        const imgProps = pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);

        // 如果不是最后一页，则添加新页
        if (index < table.childNodes.length - 1) {
          console.log('add page', index);
          pdf.addPage();
        } else {
          pdf.save('table.pdf');
        }
      });
    });
  };

  return (
    <div>
      <button onClick={exportToPdf}>导出为 PDF</button>
      <div ref={tableRef} id="table-container">
        {chunks.map((chunk, index) => {
          return (
            <div key={index}>
              {'page== ' + index}
              {chunk.map((item) => (
                <div style={{ padding: '10px' }}>
                  <span>{item.name}</span>
                  <span>{item.age}</span>
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default PdfComponent;
